//
//  JFScrumMainViewController.m
//  JobFree2.0
//
//  Created by xxcao on 2017/5/25.
//  Copyright © 2017年 Dale. All rights reserved.
//

#import "JFScrumMainViewController.h"
#import "UIViewController+MMDrawerController.h"
#import "JFScrumCollectionCell.h"
#import "MJRefresh.h"
#import "JFNoteViewController.h"
#import "BaseTabbarViewController.h"
#import "JFCreateBoardViewController.h"
#import "JFScrumModel.h"
#import "TeamOperatingView.h"

@interface JFScrumMainViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)NSMutableArray *scrumDatas;
@property (nonatomic,assign) int page;

@end

@implementation JFScrumMainViewController

static NSString *CellIdentifier = @"ScrumCell";
static NSString *CellIdentifier1 = @"ScrumCell1";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor greenColor];
    [self configureNavigationItem];
    self.title = @"看板";
    [self.collectionView registerNib:[UINib nibWithNibName:@"JFScrumCollectionCell" bundle:nil] forCellWithReuseIdentifier:CellIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:@"JFScrumCollectionCell1" bundle:nil] forCellWithReuseIdentifier:CellIdentifier1];
    
    [self pullDownRequest];
    self.page = 1;
    isRefrsh = NO;
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (isRefrsh) {
        isRefrsh = NO;
        [self loadData];
    }
}

- (void)handleLeftBtnAction {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:^(BOOL finished) {
        
    }];
}

- (void)handleRightBtnAction {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideRight animated:YES completion:^(BOOL finished) {
        
    }];
}

//MARK: pull down request and pull up request
- (void)pullDownRequest {
    //下拉刷新
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self loadData];
    }];
}

- (void)pullUpRequest {
    //上拉加载更多
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //refresh code
        self.page++;
        [self loadMoreData];
    }];
    
}

//MARK: getter
- (NSMutableArray *)scrumDatas {
    if (!_scrumDatas) {
        _scrumDatas = [NSMutableArray array];
    }
    return  _scrumDatas;
}


//MARK: loadData
- (void)loadData {
    JFScrumModel *model = [[JFScrumModel alloc] init];
    model.board_name = @"Test";
    model.board_remark = @"Test";
    model.create_date = @"2017-06-20";
    model.index = 1;
    [self.scrumDatas addObject:model];
    [self.collectionView reloadData];
    return;
    
    
    NSNumber *page = @(self.page);
    GetBoardsApi *api = [[GetBoardsApi alloc] initWithPara:page];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.responseObject);
        [self.scrumDatas removeAllObjects];
        NSData *data = [request.responseObject[@"response"] dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArr = dic[DATA];
        if ([dic[CODE] intValue] == 200) {
            for (int i = 0; i< dataArr.count; i++) {
                JFScrumModel *model = [[JFScrumModel alloc] init];
                [model setValuesForKeysWithDictionary:dataArr[i]];
                model.index = i + 1;
                [self.scrumDatas addObject:model];
            }
            [self.collectionView reloadData];
            
            if (self.scrumDatas.count >= 10) {
                [self pullUpRequest];
            } else {
                self.collectionView.mj_footer = nil;
            }
        } else {
            [super showText:dic[MESSAGE] afterSeconds:1.0];
        }
         [self.collectionView.mj_header endRefreshing];
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.error);
        [self.collectionView.mj_header endRefreshing];
        [super showText:request.error.localizedDescription afterSeconds:1.0];
        
    }];
}

- (void)loadMoreData {
    NSNumber *page = @(self.page);
    GetBoardsApi *api = [[GetBoardsApi alloc] initWithPara:page];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.responseObject);
        [self.scrumDatas removeAllObjects];
        NSData *data = [request.responseObject[@"response"] dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArr = dic[DATA];
        if ([dic[CODE] intValue] == 200) {
            
            if (dataArr.count < 10) {
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.collectionView.mj_footer endRefreshing];
            }
            
            for (int i = 0; i< dataArr.count; i++) {
                JFScrumModel *model = [[JFScrumModel alloc] init];
                [model setValuesForKeysWithDictionary:dataArr[i]];
                model.index = i;
                [self.scrumDatas addObject:model];
            }
            [self.collectionView reloadData];
        } else {
            [self.collectionView.mj_footer endRefreshing];
            [super showText:dic[MESSAGE] afterSeconds:1.0];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.error);
        [self.collectionView.mj_footer endRefreshing];
        [super showText:request.error.localizedDescription afterSeconds:1.0];
    }];
}

//MARK: 置顶
- (void)boardTopWithModel:(JFScrumModel *)model {
    BoardTopApi *api = [[BoardTopApi alloc] initWithPara:model];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.responseObject);
        NSData *data = [request.responseObject[@"response"] dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([dic[CODE] intValue] == 200) {
            [super showHudWithText:dic[MESSAGE]];
            [super hideHudAfterSeconds:1.0];
            [self loadData];
        } else {
            [super showHudWithText:dic[MESSAGE]];
            [super hideHudAfterSeconds:1.0];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.error);
        [super showHudWithText:request.error.localizedDescription];
        [super hideHudAfterSeconds:1.0];
    }];
}

//MARK: 免打扰
- (void)boardDisturbWithModel:(JFScrumModel *)model {
    BoardDisturbApi *api = [[BoardDisturbApi alloc] initWithPara:model];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.responseObject);
        NSData *data = [request.responseObject[@"response"] dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([dic[CODE] intValue] == 200) {
            [super showHudWithText:dic[MESSAGE]];
            [super hideHudAfterSeconds:1.0];
            [self loadData];
        } else {
            [super showHudWithText:dic[MESSAGE]];
            [super hideHudAfterSeconds:1.0];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.error);
        [super showHudWithText:request.error.localizedDescription];
        [super hideHudAfterSeconds:1.0];
    }];
}

//MARK: 退出
- (void)boardExitWithModel:(JFScrumModel *)model {
    BoardExitApi *api = [[BoardExitApi alloc] initWithPara:model];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.responseObject);
        NSData *data = [request.responseObject[@"response"] dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([dic[CODE] intValue] == 200) {
            [super showHudWithText:dic[MESSAGE]];
            [super hideHudAfterSeconds:1.0];
            [self loadData];
        } else {
            [super showHudWithText:dic[MESSAGE]];
            [super hideHudAfterSeconds:1.0];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.error);
        [super showHudWithText:request.error.localizedDescription];
        [super hideHudAfterSeconds:1.0];
    }];
}

//MARK: 解散
- (void)boardDismissWithModel:(JFScrumModel *)model {
    BoardDismissApi *api = [[BoardDismissApi alloc] initWithPara:model];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.responseObject);
        NSData *data = [request.responseObject[@"response"] dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([dic[CODE] intValue] == 200) {
            [super showHudWithText:dic[MESSAGE]];
            [super hideHudAfterSeconds:1.0];
            [self loadData];
        } else {
            [super showHudWithText:dic[MESSAGE]];
            [super hideHudAfterSeconds:1.0];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSLog(@"%@", request.error);
        [super showHudWithText:request.error.localizedDescription];
        [super hideHudAfterSeconds:1.0];
    }];
}

//MARK: UICollectionView DataSource and Delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _scrumDatas.count + 1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        JFScrumCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier1 forIndexPath:indexPath];
        return cell;
    } else {
        JFScrumCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.model = self.scrumDatas[indexPath.item - 1];
        cell.clickBlock = ^(JFScrumModel *model, TeamOperatingView *view, JFScrumCollectionCellClickType type) {
            if (type == JFScrumCollectionCellClickTypeTop) {
                [self boardTopWithModel:model];
            } else if (type == JFScrumCollectionCellClickTypeDistrub) {
                [self boardDisturbWithModel:model];
            } else {
                NSString *message = nil;
                BOOL isUser = [[JFUser mainJFUser].user_id isEqualToString:model.creator];
                if (isUser) {
                    message = @"你确定要解散该看板";
                } else {
                    message = @"你确定要退出该看板";
                }
                [view remove];
                if (!isUser) {
                    [self boardExitWithModel:model];
                } else {
                    [self boardDismissWithModel:model];
                }
//                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
//                UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
//                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//                    [view remove];
//                    if (isUser) {
//                        [self boardExitWithModel:model];
//                    } else {
//                        [self boardDismissWithModel:model];
//                    }
//                }];
//                [alertVC addAction:action];
//                [alertVC addAction:action1];
//                [self presentViewController:alertVC animated:YES completion:nil];
            }
        };
        return cell;
    }
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return Size(Screen_Width / 2.0, 160);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0.0;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)collectionView:(UICollectionView *)colView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [colView cellForItemAtIndexPath:indexPath];
    //设置(Highlight)高亮下的颜色
    [cell setBackgroundColor:[UIColor colorWithRed:242.0 / 255.0 green:242.0 / 255.0 blue:242.0 / 255.0 alpha:1.0]];
}

- (void)collectionView:(UICollectionView *)colView  didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [colView cellForItemAtIndexPath:indexPath];
    //    设置(Nomal)正常状态下的颜色
    [cell setBackgroundColor:[UIColor whiteColor]];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        JFCreateBoardViewController *createBoardVC = [[JFCreateBoardViewController alloc] initWithNibName:@"JFCreateBoardViewController" bundle:nil];
        [self.navigationController pushViewController:createBoardVC animated:YES];
    } else {
        BaseTabbarViewController *tabBarController = [[BaseTabbarViewController alloc] init];
        tabBarController.model = self.scrumDatas[indexPath.item - 1];
        [tabBarController loadViewControllers];
        [self.navigationController pushViewController:tabBarController animated:YES];
    }
}

@end
